var app = require('express')()
var http = require('http').Server(app)
var request = require('request')
var cors = require('cors')
require('./socket/index')(http)
const bodyParse = require('body-parser')

const { verifyToken } = require('./dao/jwt.js')
const { urlencoded } = require('body-parser')
const port = 13308
app.use(cors()) //跨域处理  /Users/hemenghao/Desktop/小贺个人/node
app.use(bodyParse.json())
app.use(bodyParse.urlencoded({ extended: true }))
    //加入中间件，进行验证token是否过期
app.use(async(req, res, next) => {
    let { url } = req
    if (url == '/')
        return res.send(`
    <div style="display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;">
    <h4 >服务是正常的，有问题就不是我的了</h4>
    <hr/>
    <p style="text-align: center">请好好对待我哦</p>
    </div>
    `)
            // 检测路径是否为登录登出
    if (url == '/login' || url == '/logout') return next()
        // // 判断是否有token传过来
    if (!req.headers.token || req.headers.token == '') return res.send({ code: 1000, msg: '未检测到token' })
        // 判断token
    if (!verifyToken(req.headers.token)) return res.send({ code: 1000, msg: 'token失效' })
    req.id = verifyToken(req.headers.token).id
        // req.id = 1
    next()
})
require('./routers/index')(app)

// // 路径404
// app.use((req, res, next) => {
//     let err = new Error('Not Found!!!')
//     next(err)
//     // console.log();
//     res.end({ code: 500, msg: 'Not Found!!!' })
//     // err.status = 404
// })
// 服务器错误
app.use((err, req, res, next) => {
    console.log(err)
    res.status(err.status || 500)
    res.end('服务器错误', err.message)
})

http.listen(port, () => {
    console.log(`端口为 ${port}`)
        // 自己请求自己 为了不让node seve 停止
    setInterval(() => {
        // request.post('http://192.168.31.202:13308/login')
    }, 150000)
})